var page = 1;

$(document).ready(function() {
	displayFaculty();
	displayProject();
	var currentUrl = window.location.href;
	if(currentUrl.indexOf('#') != -1){
		page = currentUrl.slice(currentUrl.indexOf('#') + 1);
	}
	displayProjectList(page);
	getCountProject(page);
});

$(window).bind('hashchange', function() {
	location.reload();
});

function displayProjectList(){
	var params = {
		action: 'getByLimit',
		fromProject: LIMIT_PROJECT * (parseInt(page) - 1),
		toProject: LIMIT_PROJECT
	};
	sendRequest(URL_PROJECT, 'GET', params, function(res){
		var data = JSON.parse(res);
		for(var index in data){
			$('#projectLargeList').append(drawProjectList(data[index]));
		}
	}, function(err){
	});
}

function drawProjectList(project){
	var href = PROJECT_DETAIL+'#'+project.Id;
	var image = drawDiv('col-md-6 col-lg-6 col-sm-6');
	image.append(drawA(THUMBNAIL, href, '').append(drawImage(project.Image)));
	var name = drawDiv('col-md-6 col-lg-6 col-sm-6');
	name.append($('<h4/>').append(drawA('', href, '').append(drawLabel(CONTROL_LABEL, project.Title))));
	name.append(drawP(TIME,'').append(drawSpan(SPAN_CALENDAR,'')).append(drawSpan('',project.Date)));
	name.append(drawP(FORM_CONTROL_STATIC,'').append(drawA('', href,'Chi tiết')));
	var summary = drawDiv('col-xs-12');
	summary.append($('<hr/>')).append(drawP(FORM_CONTROL_STATIC, project.Summary));
	var row = drawDiv('row').append(image).append(name).append(summary);
	return drawDiv('col-xs-6').append(drawDiv('panel panel-default panel-project').append(drawDiv('panel-body').append(row)));
}

function getCountProject(currentPage){
	var params = {
		action: 'getCountRow'
	};
	sendRequest(URL_PROJECT, 'GET', params, function(res){
		var data = JSON.parse(res);
		var countPage = Math.round(data.countRow / LIMIT_PROJECT);
		if(data.countRow % LIMIT_PROJECT > 0 && data.countRow % LIMIT_PROJECT < LIMIT_PROJECT/2){
			countPage++;
		}
		$('#pageList').html('');
		if(currentPage > countPage){
			currentPage = countPage;
		}
		if(currentPage > 5){
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage - 1)));
			$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage)));
			if(currentPage + 1 < countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, currentPage + 1)));
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			} else if(currentPage + 1 == countPage){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, countPage)));
			}
		} else {
			for(var index = 1; index <= countPage; index++){
				$('#pageList').append(drawLi('').append(drawA('', '#'+index, index)));
			}
		}
	}, function(err){
	});
}